﻿using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace dot_in.HTWKAidStation.Client.Menu
{
    public class MenuParser
    {
        private string html;

        public MenuParser(string html)
        {
            this.html = MenuParser.PreFilterHtml(html);
        }

        public List<MenuItem> GetAllMenuItems()
        {
            return SplitMenuItems(this.html).Select(ParseMenuItem).ToList();
        }

        private static string PreFilterHtml(string html)
        {
            int start = Regex.Match(html, "<div class=.menu.>").Index;
            string result = html.Substring(start, Regex.Match(html, "(?<=<div class=.menu.>).+?(<input)", RegexOptions.Singleline).Groups[1].Index - start);
            return result;
        }

        private static IEnumerable<string> SplitMenuItems(string html)
        {
            List<string> result = new List<string>();
            Match match = Regex.Match(html, "<div class=.menu.>");
            match = match.NextMatch();
            while (match.Success)
            {
                result.Add(html.Substring(0, match.Index));
                html = html.Substring(match.Index);
                match = Regex.Match(html, "<div class=.menu.>");
                match = match.NextMatch();
            }

            result.Add(html);

            return result;
        }

        private static MenuItem ParseMenuItem(string html)
        {
            MenuItem result = new MenuItem
                                  {
                                      ItemTitle =
                                          Regex.Match(html, ".menu_title.><span>([^<]*?)</span>").Groups[1].Value,
                                      SubTitle = Regex.Match(html, ".menu_name1.>([^<]*?)</div>").Groups[1].Value,
                                      Content = ParseItemContent(html),
                                      PriceString = ParseItemPrice(html)
                                  };

            return result;
        }

        private static string ParseItemContent(string html)
        {
            string result = Regex.Matches(html, ".menu_name2.>([^<]*?)</div>").Cast<Match>().Aggregate(string.Empty, (current, match) => current + (match.Groups[1].Value + ", "));
            result = result.TrimEnd(new[] {',', ' '});
            return result;
        }

        private static string ParseItemPrice(string html)
        {
            string result = Regex.Replace(Regex.Match(html, ".menu_price.>([^<]*?)</div>").Groups[1].Value, "&euro;", "€");
            return result;
        }
    }
}
